package com.huawei.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huawei.annotation.ConstraintsJustryDeng;
import com.huawei.config.MyBean;
import com.huawei.po.GenshinGame;
import com.huawei.po.TestService;
import com.huawei.po.User;
import com.huawei.po.XxxTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author wujinpeng
 * @version 1.0
 * @date 2025/1/23 15:26
 * @description
 */
@RestController
@RequestMapping("/wjp")
@Validated
public class TestController {

    @Autowired
    private ObjectMapper objectMapper;

    @GetMapping("/test")
    public String test(@NotBlank(message = "不能为空！") String name) throws JsonProcessingException {
        String[] strings = {"1", "2", "3"};
        String json = objectMapper.writeValueAsString(strings);
        List<String> readValue = objectMapper.readValue(json, new TypeReference<List<String>>() {
        });
        readValue.set(0, "5");
        System.out.println(readValue);
        System.out.println(Arrays.toString(strings));

        return name;
    }

    @PostMapping("/test1")
    public String test1(@Validated @RequestBody User user) {
        return user.toString();
    }

    @GetMapping("/test2")
    public String test2(
            @ConstraintsJustryDeng(message = "需要包含特定信息!", contains = "测试1", statusType = {"2", "3", "4"})
            String name) {
        return name;
    }

    @GetMapping("/test3")
    public Integer test2(
            @ConstraintsJustryDeng(message = "只能在三个年龄里！", contains = "测试2", statusType = {"1", "18", "25"})
            Integer age) {
        return age;
    }

    @GetMapping("/test4")
    public String test4(@Validated User user) {
        return user.toString();
    }

    @PostMapping("/test5")
    public String test5(@Validated @RequestBody GenshinGame genshinGame) {
        return genshinGame.toString();
    }

    @Autowired
    private MyBean myBean;

    @GetMapping("/test6")
    public String test4(XxxTypeEnum xxxTypeEnum) {
        TestService testService = myBean.get(xxxTypeEnum);
        if (testService != null) {
            return testService.test();
        }
        return "不存在该业务！";
    }

//    @GetMapping("/test7")
    @GetMapping("${test.value:/test222}")
    public void test7() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        String test = request.getHeader("test");
        System.out.println(test);
        System.out.println("test7 get success");
    }

//    @Value("classpath:myfile/test.txt")
//    private Resource resource;

    @Autowired
    private ResourceLoader resourceLoader;

    @GetMapping("/test8")
    public String test8() throws IOException {
//        ClassLoader classLoader = getClass().getClassLoader();
        String line = "";
//        Resource resource = resourceLoader.getResource("classpath:myfile/test.txt");
//        Resource resource = resourceLoader.getResource("file:D:/AAA-code/java_code/springboot-compoentTest/log2/logback.2025-01-25.0.log");
        Resource resource = new ClassPathResource("myfile/test.txt");

        if (resource.exists()) {
            InputStream resourceAsStream = resource.getInputStream();
            if (resourceAsStream == null) {
                System.out.println("File not found");
                return "File not found";
            }
            System.out.println("file path :" + resource.getURI());
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceAsStream))) {
                line = reader.readLine();
                if (line != null) {
                    System.out.println(line);
                } else {
                    System.out.println("File is empty");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return line;
    }



    public static void main(String[] args) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

        Runnable task = () -> {
            System.out.println(Thread.currentThread().getName());
            System.out.println("Task executed at: " + System.currentTimeMillis());
        };
        Runnable task2 = () -> {
            try {
                Thread.sleep(3000);
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("Task2 executed at: " + System.currentTimeMillis());

        };


        // 每隔2秒执行一次任务，延迟1秒启动
//        scheduler.scheduleAtFixedRate(task, 1, 2, TimeUnit.SECONDS);
        scheduler.scheduleAtFixedRate(task2, 1, 2, TimeUnit.SECONDS);

        // 如果需要，可以在特定条件下关闭调度器
        Runtime.getRuntime().addShutdownHook(new Thread(scheduler::shutdown));
    }
}
